# coding:utf-8
from typing import Optional

from fastapi import APIRouter, Query, Path
from tortoise.expressions import Q

from app.admin.schemas.system import PostBase, PostUpdate
from app.admin.schemas.upload import FolderBase
from app.admin.service.system.post import SystemPostService
from app.core.response import SuccessExtra, Success, Fail


router = APIRouter()


@router.get("/list", summary="文件列表")
async def page_list(
        page: int = Query(1, description="页码"),
        limit: int = Query(10, description="每页数量"),
        name: str = Query(None, description="文件名称，用于搜索"),
        file_type: Optional[str] = Query(None, description="文件类型"),
):
    # 查询条件
    query = Q()
    if name:
        query &= Q(name__contains=name)
    if file_type and int(file_type) in [0, 10, 20,30,40]:
        query &= Q(file_type__lt=file_type)
    model_service = SystemPostService()
    total, lists = await model_service.page_list(query, page, limit)
    data = [await obj.to_dict(m2m=True) for obj in lists]
    # return data
    return SuccessExtra(data=data, total=total, page=page, limit=limit)


@router.get("/file/{item_id}", summary="查看文件")
async def get_detail(item_id: int = Path(..., description="文件ID"), ):
    model_service = SystemPostService()
    user_obj = await model_service.get_id(item_id)
    if not user_obj:
        return Fail(msg="文件不存在")
    user_dict = await user_obj.to_dict(exclude_fields=["password"])
    return Success(data=user_dict)


@router.post("/file/rename", summary="文件重命名")
async def update_user(data_in: PostUpdate):
    model_service = SystemPostService()
    user = await model_service.update(obj_in=data_in)
    # await model_service.update_roles(user, user_in.roles)
    return Success(msg="Updated Successfully")


@router.delete("/file/delete/{item_id}", summary="删除文件")
async def delete_user(item_id: int = Path(..., description="文件ID")):
    model_service = SystemPostService()
    await model_service.remove(item_id)
    return Success(msg="Deleted Successfully")


@router.get("/folder", summary="文件夹列表")
async def page_list(
        name: str = Query(None, description="文件名称，用于搜索"),
):
    # 查询条件
    query = Q()
    if name:
        query &= Q(name__contains=name)
    model_service = SystemPostService()
    lists = await model_service.page_list(query)
    data = [await obj.to_dict(m2m=True) for obj in lists]
    # return data
    return SuccessExtra(data=data)


@router.post("/folder/create", summary="创建文件夹")
async def create_user(user_in: FolderBase):
    model_service = AdminService()
    # 构建查询条件
    query = Q(username__lt=user_in.username)
    user = await model_service.find(query)
    if user:
        return Fail(msg="The user with this email already exists in the system.")
    new_user = await model_service.create(obj_in=user_in)
    # await model_service.update_roles(new_user, user_in.roles)
    if not new_user:
        return Fail(msg="用户创建失败")
    return Success(msg="Created Successfully")

@router.post("/folder/update", summary="更新用户")
async def update_user(data_in: FolderBase):
    model_service = AdminService()
    user = await model_service.update(obj_in=data_in)
    # await model_service.update_roles(user, user_in.roles)
    return Success(msg="Updated Successfully")


@router.delete("/folder/delete/{item_id}", summary="删除用户")
async def delete_user(item_id: int = Path(..., description="用户ID")):
    model_service = AdminService()
    await model_service.remove(item_id)
    return Success(msg="Deleted Successfully")